/*
 * @Author: your name
 * @Date: 2024-05-05 11:02:38
 * @LastEditTime: 2024-05-05 14:40:41
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\450.删除二叉搜索树中的节点.cpp
 */
/*
 * @lc app=leetcode.cn id=450 lang=cpp
 *
 * [450] 删除二叉搜索树中的节点
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if(root == nullptr){
            return root;
        }
        if(root->val == key){
            // 当前节点是叶子结点
            if(root->left == nullptr && root->right == nullptr){
                delete root;
                return nullptr;
            }
            else if(root->left == nullptr){
                auto node = root->right;
                delete root;
                return node;
            }
            else if( !root->right){
                auto node = root->left;
                delete root;
                return node;
            }
            else{
                // 找到右子树最左的孩子
                TreeNode* cur = root->right;
                TreeNode* resNode = root->right;
                while(cur->left){
                    cur = cur->left;
                }
                TreeNode* node = root->left;
                delete root;
                // 接上
                cur->left = node;
                return resNode;
            }
        }
        if(root->val > key) root->left = deleteNode(root->left, key);
        if(root->val < key) root->right = deleteNode(root->right, key);
        return root;
        
    }
};
// @lc code=end

